<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />

<div style="padding: 20px;">
    <h3><i class="layui-icon layui-icon-add-1"></i> 新增工艺流程</h3>
    
    <!-- 基础信息 -->
    <div class="layui-card" style="margin-top:10px;">
        <div class="layui-card-header">基础信息</div>
        <div class="layui-card-body">
            <form class="layui-form" lay-filter="flow-form" action="">
                <div class="layui-row layui-col-space20">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">工艺流程编号</label>
                            <div class="layui-input-inline" style="width: 260px;">
                                <input type="text" name="flowCode" id="flowCode" placeholder="系统自动生成" autocomplete="off" class="layui-input" readonly>
                            </div>
                            <div class="layui-input-inline" style="width: 80px;">
                                <button type="button" class="layui-btn layui-btn-sm" onclick="generateFlowCode()">生成编号</button>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">工艺流程名称</label>
                            <div class="layui-input-inline" style="width: 260px;">
                                <input type="text" name="flowName" placeholder="请输入工艺流程名称" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-row layui-col-space20">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">负责人</label>
                            <div class="layui-input-inline">
                                <select name="responsible" lay-filter="responsible">
                                    <option value="">请选择负责人</option>
                                    <option value="张三">张三</option>
                                    <option value="李四">李四</option>
                                    <option value="王五">王五</option>
                                    <option value="赵六">赵六</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">所属部门</label>
                            <div class="layui-input-inline">
                                <select name="department" lay-filter="department">
                                    <option value="">请选择部门</option>
                                    <option value="生产部">生产部</option>
                                    <option value="加工部">加工部</option>
                                    <option value="打包部">打包部</option>
                                    <option value="运输部">运输部</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">工序数量</label>
                        <div class="layui-input-inline" style="width: 260px;">
                            <input type="text" name="flowNumber" placeholder="请输入数量" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-row layui-col-space20">
                    <div class="layui-col-md6">
                        <div class="layui-form-item" pane>
                            <label class="layui-form-label">状态</label>
                            <div class="layui-input-block">
                                <input type="radio" name="processStatus" value="true" title="启用" checked>
                                <input type="radio" name="processStatus" value="false" title="禁用">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">备注</label>
                    <div class="layui-input-block">
                        <textarea name="remark" placeholder="请输入备注" class="layui-textarea"></textarea>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 加工工序 -->
    <div class="layui-card" style="margin-top:10px;">
        <div class="layui-card-header">加工工序</div>
        <div class="layui-card-body">
            <div class="layui-btn-group" style="margin-bottom:10px;">
                <button type="button" class="layui-btn layui-btn-sm" id="btnAddProcess">添加</button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="btnRemoveProcess">移除</button>
            </div>

            <table class="layui-table" lay-size="sm">
                <thead>
                    <tr>
                        <th style="width:50px;"><input type="checkbox" lay-skin="primary" lay-filter="chkAll"></th>
                        <th style="width:60px;">序号</th>
                        <th style="width:90px;">加工工序</th>
                        <th style="width:120px;">工序编码</th>
                        <th style="width:120px;">工序名称</th>
                        <th style="width:100px;">负责人</th>
                        <th style="width:100px;">所属部门</th>
                        <th style="width:180px;">备注</th>
                        <th style="width:120px;">操作</th>
                    </tr>
                </thead>
                <tbody id="processBody">
                    <!-- 动态行区域：从弹窗选择后追加到这里，仅展示不提交 -->
                </tbody>
            </table>
            <!-- 选中的工序ID集合（仅存储，提交时可直接取值） -->
            <input type="hidden" id="processIdsInput" name="processIds" value="[]" />

            <!-- 工序列表-->
            <div id="dlgSelectProcess" style="display:none;padding:10px;">
                <div class="layui-form" style="margin-bottom:10px;">
                    <div class="layui-inline">
                        <input type="text" id="dlgKw" placeholder="工序编码/名称" autocomplete="off" class="layui-input">
                    </div>
                    <button class="layui-btn layui-btn-sm" type="button" id="dlgSearch">查询</button>
                </div>
                <table class="layui-table" lay-size="sm">
                    <thead>
                        <tr>
                            <th style="width:50px;"><input type="checkbox" id="dlgChkAll" lay-skin="primary"></th>
                            <th style="width:60px;">序号</th>
                            <th style="width:120px;">工序编码</th>
                            <th style="width:180px;">工序名称</th>
                            <th style="width:120px;">负责人</th>
                            <th style="width:120px;">所属部门</th>
                        </tr>
                    </thead>
                    <tbody id="dlgProcessBody"></tbody>
                </table>
                <div id="dlgPager" style="text-align:right;"></div>
                <div style="text-align:right;margin-top:10px;">
                    <button class="layui-btn layui-btn-primary layui-btn-sm" type="button" id="dlgCancel">取消</button>
                    <button class="layui-btn layui-btn-sm" type="button" id="dlgOk">确定</button>
                </div>
            </div>

            <div class="layui-form-item" style="text-align:right;">
                <button class="layui-btn" id="btnSave" type="button">确定</button>
                <button class="layui-btn layui-btn-primary" id="btnCancel" type="button">关闭</button>
            </div>
        </div>
    </div>
</div>


<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/layui/layui.js"></script>

<script>
    layui.use(['form', 'layer', 'laypage'], function () {
        var form = layui.form;
        var layer = layui.layer;
        var laypage = layui.laypage;
        
        // 声明弹窗相关变量
        var dlgIndex = null;
        var dlgPageIndex = 1;
        var dlgPageSize = 10;
        var dlgTotal = 0;
        
        // 页面加载完成后自动生成编号
        $(document).ready(function() {
            generateFlowCode();
        });
        
        // 自动生成工艺流程编号
        function generateFlowCode() {
            var currentDate = new Date();
            var year = currentDate.getFullYear();
            var month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
            var day = currentDate.getDate().toString().padStart(2, '0');
            var sequence = (Math.floor(Math.random() * 9000) + 1000).toString(); // 生成4位随机序号
            var flowCode = 'F' + year + month + day + sequence;
            $('#flowCode').val(flowCode);
        }
        
        var processIds = [];

        function updateProcessIdsInput() {
            $('#processIdsInput').val(JSON.stringify(processIds));
        }

        // 将弹层容器移到 body，避免在表格区域出现任何占位渲染
        var $dlg = $('#dlgSelectProcess');
        $dlg.appendTo('body').hide();


        // 点击"确定"按钮提交表单
        $('#btnSave').on('click', function () {
            submitForm();
        });

        // 点击"关闭"按钮
        $('#btnCancel').on('click', function () {
            if (window.parent && window.parent.loadPage) {
                window.parent.loadPage('/Process/ProcessFlowList', '工艺流程管理');
            } else {
                location.href = '/Process/ProcessFlowList';
            }
        });

        // 提交表单
        function submitForm() {
            // 验证必填字段
            var flowCode = $('input[name="flowCode"]').val().trim();
            var flowName = $('input[name="flowName"]').val().trim();
            var flowNumber = $('input[name="flowNumber"]').val().trim();
            var responsible = $('select[name="responsible"]').val();
            var department = $('select[name="department"]').val();
            var processStatus = $('input[name="processStatus"]:checked').val();

            if (!flowCode) {
                layer.msg('请输入工艺流程编号', { icon: 2 });
                $('input[name="flowCode"]').focus();
                return;
            }

            if (!flowName) {
                layer.msg('请输入工艺流程名称', { icon: 2 });
                $('input[name="flowName"]').focus();
                return;
            }

            if (!responsible) {
                layer.msg('请选择负责人', { icon: 2 });
                return;
            }

            if (!department) {
                layer.msg('请选择所属部门', { icon: 2 });
                return;
            }

            if (processIds.length === 0) {
                layer.msg('请至少选择一个工序', { icon: 2 });
                return;
            }

            // 收集工序备注信息
            var processRemarks = [];
            $('#processBody tr').each(function () {
                var $tr = $(this);
                var processId = $tr.data('id');
                var remark = $tr.find('td:eq(7) input[type="text"]').val().trim() || '';

                if (processId) {
                    processRemarks.push({
                        processId: processId,
                        remark: remark
                    });
                }
            });

            // 构建提交数据
            var request = {
                flowCode: flowCode,
                flowName: flowName,
                flowNumber: flowNumber, // 如果后端需要，可以添加输入字段
                responsible: responsible,
                department: department,
                status: processStatus === 'true' ? 1 : 0,
                remark: $('textarea[name="remark"]').val().trim(),
                processIds: processIds
            };

            // 显示提交中状态
            var $btn = $('#btnSave');
            var originalText = $btn.text();
            $btn.prop('disabled', true).text('提交中...');

            // 提交到后端API
            $.ajax({
                url: 'http://localhost:5141/api/ProcessFlow/CreateProcessFlow',
                type: 'POST',
                data: JSON.stringify(request),
                contentType: 'application/json',
                success: function (res) {
                    $btn.prop('disabled', false).text(originalText);

                    if (res && res.data>0) {
                        layer.msg('工艺流程创建成功！', { icon: 1, time: 2000 }, function () {
                            // 成功后跳转到工艺流程列表页面
                            if (window.parent && window.parent.loadPage) {
                                window.parent.loadPage('/Process/ProcessFlowList', '工艺流程管理');
                            } else {
                                location.href = '/Process/ProcessFlowList';
                            }
                        });
                    } else {
                        var errorMsg = res && res.message ? res.message : '创建失败，请重试';
                        layer.msg(errorMsg, { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    $btn.prop('disabled', false).text(originalText);
                    console.error('请求失败:', error);
                    layer.msg('网络请求失败，请检查网络连接', { icon: 2 });
                }
            });
        }

        // 点击“添加”打开弹窗
        $('#btnAddProcess').on('click', function () {
            dlgPageIndex = 1; 
            $('#dlgKw').val('');
            dlgIndex = layer.open({
                type: 1,
                title: '添加工序', 
                area: ['900px', '600px'], 
                shadeClose: true,
                content: $dlg,
                success: function () {
                    loadDlgList();
                },
                end: function () {
                    $dlg.hide().appendTo('body');
                    dlgIndex = null; // 重置弹窗索引
                }
            });
        });

        // 查询
        $('#dlgSearch').on('click', function () { dlgPageIndex = 1; loadDlgList(); });

        // 全选
        $(document).on('change', '#dlgChkAll', function () {
            $('#dlgProcessBody input[type="checkbox"]').prop('checked', $(this).prop('checked'));
        });

        // 取消
        $('#dlgCancel').on('click', function () { 
            if (dlgIndex) {
                layer.close(dlgIndex);
                dlgIndex = null;
            }
        });

        // 确定：把选中的工序追加到下方表格（仅展示，不提交），并把ID加入processIds
        $('#dlgOk').on('click', function () {
            var rows = [];
            $('#dlgProcessBody tr').each(function () {
                var $tr = $(this);
                if ($tr.find('input[type="checkbox"]').prop('checked')) {
                    rows.push({
                        id: $tr.data('id'),
                        code: $tr.data('code'),
                        name: $tr.data('name'),
                        res: $tr.data('res'),
                        dept: $tr.data('dept')
                    });
                }
            });
            if (rows.length === 0) { layer.msg('请选择工序'); return; }

            var start = $('#processBody tr').length;
            var html = '';
            rows.forEach(function (r, i) {
                // 已存在则跳过（避免重复添加）
                if ($('#processBody tr[data-id="' + r.id + '"]').length > 0) { return; }
                html += '<tr data-id="' + r.id + '">'
                    + '<td><input type="checkbox" lay-skin="primary"></td>'
                    + '<td>' + (start + i + 1) + '</td>'
                    + '<td>' + (start + i + 1) + '</td>'
                    + '<td>' + (r.code || '') + '</td>'
                    + '<td>' + (r.name || '') + '</td>'
                    + '<td>' + (r.res || '') + '</td>'
                    + '<td>' + (r.dept || '') + '</td>'
                    + '<td><input type="text" placeholder="请输入备注" class="layui-input"></td>'
                    + '<td><a href="javascript:;" class="layui-btn layui-btn-xs" data-action="up">上移</a>'
                    + '    <a href="javascript:;" class="layui-btn layui-btn-xs" data-action="down">下移</a>'
                    + '    <a href="javascript:;" class="layui-btn layui-btn-danger layui-btn-xs" data-action="remove">移除</a></td>'
                    + '</tr>';
                // 记录ID
                if (processIds.indexOf(r.id) === -1) { processIds.push(r.id); }
            });
            $('#processBody').append(html);
            refreshOrderNumbers();
            updateProcessIdsInput();
            if (dlgIndex) {
                layer.close(dlgIndex);
                dlgIndex = null;
            }
        });

        // 弹窗内加载工序列表（使用你的接口）
        function loadDlgList() {
            var kw = $('#dlgKw').val() || '';
            $.ajax({
                url: 'http://localhost:5141/api/Process/ShowProcessinfo',
                type: 'GET',
                data: { pageindex: dlgPageIndex, pagesize: dlgPageSize, processCode: kw, processName: kw },
                success: function (res) {
                    var list = (res && res.pageData) ? res.pageData : [];
                    dlgTotal = res ? (res.totalCount || 0) : 0;
                    var rows = '';
                    list.forEach(function (it, i) {
                        rows += '<tr data-id="' + it.id + '" data-code="' + (it.processCode || '') + '" data-name="' + (it.processName || '') + '" data-res="' + (it.responsible || '') + '" data-dept="' + (it.department || '') + '">'
                            + '  <td><input type="checkbox" lay-skin="primary"></td>'
                            + '  <td>' + (((dlgPageIndex - 1) * dlgPageSize) + i + 1) + '</td>'
                            + '  <td>' + (it.processCode || '') + '</td>'
                            + '  <td>' + (it.processName || '') + '</td>'
                            + '  <td>' + (it.responsible || '') + '</td>'
                            + '  <td>' + (it.department || '') + '</td>'
                            + '</tr>';
                    });
                    $('#dlgProcessBody').html(rows);

                    laypage.render({
                        elem: 'dlgPager',
                        count: dlgTotal,
                        limit: dlgPageSize,
                        layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'],
                        jump: function (obj, first) {
                            if (!first) { 
                                dlgPageIndex = obj.curr; 
                                dlgPageSize = obj.limit; 
                                loadDlgList(); 
                            }
                        }
                    });
                },
                error: function(xhr, status, error) {
                    console.error('加载工序列表失败:', error);
                    layer.msg('加载工序列表失败，请重试', {icon: 2});
                    $('#dlgProcessBody').html('<tr><td colspan="6" style="text-align:center;color:#999;">加载失败，请重试</td></tr>');
                }
            });
        }

        // 统一刷新下方表格的序号列
        function refreshOrderNumbers() {
            $('#processBody tr').each(function (idx) {
                var num = idx + 1;
                $(this).children('td').eq(1).text(num); // 序号
                $(this).children('td').eq(2).text(num); // 加工工序
            });
        }

        // 简单上移/下移/移除
        $(document).on('click', '#processBody a[data-action="remove"]', function () {
            var $tr = $(this).closest('tr');
            var id = $tr.data('id');
            $tr.remove();
            if (id !== undefined) {
                processIds = processIds.filter(function (x) { return x !== id; });
                updateProcessIdsInput();
            }
            refreshOrderNumbers();
        });
        $(document).on('click', '#processBody a[data-action="up"]', function () { var tr = $(this).closest('tr'), p = tr.prev(); if (p.length) { tr.insertBefore(p); refreshOrderNumbers(); } });
        $(document).on('click', '#processBody a[data-action="down"]', function () { var tr = $(this).closest('tr'), n = tr.next(); if (n.length) { tr.insertAfter(n); refreshOrderNumbers(); } });
    });

</script>
